import axios from 'axios'
import { Message } from 'element-ui'
import { saveAs } from 'file-saver'
import { getToken } from '@/utils/auth'
import { blobValidate } from '@/utils/ruoyi'

const baseURL = process.env.VUE_APP_BASE_API

export function download(resource) {
  var url = baseURL + '/common/download/resource?resource=' + encodeURI(resource)
  axios({
    method: 'get',
    url: url,
    responseType: 'blob',
    headers: { Authorization: 'Bearer ' + getToken() }
  }).then(async (res) => {
    const isLogin = await blobValidate(res.data)
    if (isLogin) {
      const blob = new Blob([res.data])
      saveAs(blob, decodeURI(res.headers['download-filename']))
    } else {
      const resText = await res.data.text()
      const rspObj = JSON.parse(resText)
      Message.error(rspObj.msg)
    }
  })
}